<template>
  <div>
    <div class="pp-t-96">
      <h3 class="fw-b fs-14">模板管理</h3>

      <!-- 筛选条件与查询 -->
      <a-form-model layout="inline" :model="search">
        <a-row :gutter="16">
          <a-col :span="4">
            <a-form-model-item label="" style="width: 100%">
              <a-input
                v-model="search.templateName"
                class="ct-input"
                style="width: 100%"
                placeholder="模板名称"
              >
                <a-icon slot="suffix" :component="require('@/assets/icon/search.svg')" @click="changeTable({current:1})" />
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="" style="width: 100%">
              <airModel v-model="search.model" style="width: 100%" @change="changeTable({current:1})" />
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="" style="width: 100%">
              <a-select
                v-model="search.smi"
                show-arrow
                style="width: 100%"
                placeholder="一级分类"
                allow-clear
                @change="(v)=>{
                  getImiListHanlder(v,false);
                  changeTable({current:1})
                }"
              >
                <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
                <a-select-option v-for="selectItem in firstClassClassificationList" :key="selectItem.id" :value="selectItem.name">
                  {{ selectItem.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="" style="width: 100%">
              <a-select
                v-model="search.imi"
                show-arrow
                style="width: 100%"
                placeholder="二级分类"
                allow-clear
                @change="changeTable({current:1})"
              >
                <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
                <a-select-option v-for="selectItem in secondaryClassificationList" :key="selectItem.id" :value="selectItem.name">
                  {{ selectItem.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="" style="width: 100%">
              <a-select
                v-model="search.enable"
                show-arrow
                style="minWidth: 130px"
                placeholder="状态"
                allow-clear
                @change="changeTable({current:1})"
              >
                <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
                <a-select-option v-for="selectItem in enableList" :key="selectItem.value" :value="selectItem.value">
                  {{ selectItem.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item>
              <a-button type="default" ghost :loading="repReportTemplateLoading" @click="resetSearchHandler">
                重置
              </a-button>

            </a-form-model-item>
          </a-col>
        </a-row></a-form-model>
    </div>
    <!-- table -->
    <div class="pp-rb-box">
      <a-button type="primary" ghost :loading="repReportTemplateLoading" @click="addVisible=true">
        新增
      </a-button>
      <a-table
        class="mt-15 table-border"
        :columns="columns"
        size="middle"
        :data-source="repReportTemplateList"
        :row-key="(row,index) => row.id"
        :pagination="{
          showTotal:(total)=> `共 ${total} 条数据`,
          showSizeChanger: true,//设置每页显示数据条数
          showQuickJumper: true,
          size:'big',
          current:paginationOptions.pageNum,
          pageSize:paginationOptions.pageSize,
          total:paginationOptions.total
        }"
        :loading="repReportTemplateLoading"
        @change="changeTable"
      />

      <!-- <a-spin :spinning="repReportTemplateLoading">
      <vxe-grid
        ref="xTable1"
        class="event-trigger-packet-upload mt-15"
        show-overflow
        highlight-hover-row
        :columns="columns"
        :data="repReportTemplateList"
        height="640"
        :sort-config="{trigger: 'cell'}"
      />
    </a-spin> -->
      <!-- add -->
      <a-modal
        v-model="addVisible"
        :mask-closable="false"
        title=""
        class="rt-i-modal"
        centered
        :confirm-loading="addRepReportTemplateLoading"
        @ok="addConfirmHandler"
        @cancel="cancelHandler"
      >
        <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

        <div class="c-dialog-title fw-500">{{ addTitle }}模板</div>
        <a-form-model
          ref="addForm"
          :model="addForm"
          :rules="addRules"
          layout="horizontal"
        >
          <a-form-model-item label="模板名称" prop="templateName">
            <a-input v-model="addForm.templateName" placeholder="模板名称" class="input-type-o" style="width: 100%" />
          </a-form-model-item>
          <a-form-model-item label="归属一级分类" class="input-type-o" prop="smi">
            <a-select
              v-model="addForm.smi"
              show-arrow
              style="width: 100%"
              placeholder="归属一级分类"
              allow-clear
              class="input-type-o"
              @change="(v)=>getImiListHanlder(v,true)"
            >
              <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
              <a-select-option v-for="selectItem in firstClassClassificationList" :key="selectItem.id" :value="selectItem.name">
                {{ selectItem.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item label="归属二级分类" prop="imi">
            <a-select
              v-model="addForm.imi"
              show-arrow
              style="width: 100%"
              placeholder="归属二级分类"
              class="input-type-o"
              allow-clear
            >
              <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
              <a-select-option v-for="selectItem in secondaryClassificationListModel" :key="selectItem.id" :value="selectItem.name">
                {{ selectItem.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="机号限制" prop="tailNumbers">
            <tailNumber v-model="addForm.tailNumbers" class="input-type-o" :max-tag-count="3" value-key="tailnumber" name-key="tailnumber" />
          </a-form-model-item>
          <!-- <a-form-model-item label="生效时间" prop="effectTime">
            <a-date-picker
              v-model="addForm.effectTime"
              style="width: 100%;min-width: 100%;"
              format="YYYY-MM-DD HH:mm:ss"
              class="input-type-o"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="生效时间"
              show-time
            />
          </a-form-model-item> -->
          <a-form-model-item prop="description">
            <span slot="label">描述<span class="text-color-9ea5b2 fs-12">选填</span></span>
            <a-textarea
              v-model="addForm.description"
              style="width: 100%"
              placeholder="描述"
              class="input-type-o"
              :auto-size="{ minRows: 5, maxRows: 8 }"
            />
          </a-form-model-item>
          <a-form-model-item label="模板状态" prop="enable">

            <a-radio-group v-model="addForm.enable" :default-value="1">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="0">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>

  </div>
</template>

<script>
import rowClass from '@/pages/common/rowClass';
import getSmiAndModel from '../getSmiAndModel';
import { mapState, mapActions, mapMutations } from 'vuex';
import tailNumber from '@/pages/components/tailNumber';
import airModel from '@/pages/components/airModel';
export default {
  components: {
    tailNumber,
    airModel
  },
  mixins: [rowClass, getSmiAndModel],
  data() {
    return {
      addVisible: false,
      addTitle: '新增',
      addForm: {
        enable: 1
      },
      addRules: Object.freeze({
        templateName: [
          { required: true, message: '请填写', trigger: 'blur' }
        ],
        smi: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        imi: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        tailNumbers: [
          { required: true, type: 'array', message: '请选择', trigger: 'change' }
        ]
      }),
      enableList: Object.freeze([
        {
          name: '启用',
          value: 1,
          color: 'green'
        },
        {
          name: '禁用',
          value: 0,
          color: 'red'
        }
      ]),
      search: {},
      columns: Object.freeze([
        {
          title: '模板名称',
          align: 'left',
          width: 150,
          dataIndex: 'templateName',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '模板描述',
          align: 'left',
          width: 100,
          dataIndex: 'description',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '归属一级分类',
          align: 'left',
          dataIndex: 'smi',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '归属二级分类',
          align: 'left',
          dataIndex: 'imi',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '版本号',
          align: 'left',
          dataIndex: 'version',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '机号',
          align: 'left',
          ellipsis: true,
          dataIndex: 'tailNumbers',
          customRender: (value) => {
            return <a-tooltip placement='bottomRight'>
              <template slot='title'>
                {value?.join() ?? '--'}
              </template>
              <span>{value?.join() ?? '--'}</span>
            </a-tooltip>;
          }
        },
        {
          title: '状态',
          align: 'left',
          dataIndex: 'enable',
          customRender: (value) => {
            const item = this.enableList.find(item => item.value === value) ?? {};
            return item.name ?? '--';
          }
        },
        {
          title: '创建人',
          align: 'left',
          dataIndex: 'createBy',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '创建时间',
          align: 'left',
          width: 120,
          dataIndex: 'createTime',
          customRender: (value) => {
            return value ? this.$moment.utc(value) : '--';
          }
        },
        {
          title: '操作',
          align: 'left',
          dataIndex: 'option',
          width: 148,
          customRender: (value, record, index) => {
            const { id, enable } = record;
            return [
              <a-button size='small' type='link' onClick={() => this.modifyHandler(record)}>修改</a-button>,

              <a-button size='small' type='link' onClick={() => this.goVersion(record)}>版本管理</a-button>,
              <a-dropdown placement='bottomRight' overlayClassName='tmp-drop-down' overlay={() => {
                return (
                  <a-menu >

                    <a-menu-item>
                      <a-popconfirm
                        title={`确认${enable ? '禁用' : '启用'}?`}
                        ok-text='确认'
                        cancel-text='取消'
                        onConfirm={() => this.changeEnableHandler(id, enable, index)}
                        onClick={(e) => {
                          e.stoppropagation();
                        }}
                      >
                        <div>
                          {enable ? '禁用' : '启用'}
                        </div>
                      </a-popconfirm>
                    </a-menu-item>

                    <a-menu-item>
                      <a-popconfirm
                        title={`确认复制此项?`}
                        ok-text='确认'
                        cancel-text='取消'
                        onConfirm={() => this.copyItemHandler(record)}
                      >
                        <div>
                        复制
                        </div>
                      </a-popconfirm>
                    </a-menu-item>
                    <a-menu-item>
                      <a-popconfirm
                        title='确认删除此项?'
                        ok-type='danger'
                        ok-text='确认'
                        cancel-text='取消'
                        onConfirm={(e) => this.delItemHandler(id)}
                      >
                        <div>
                      删除
                        </div>
                      </a-popconfirm>
                    </a-menu-item>
                  </a-menu>
                );
              }}>
                <a-icon component={require('@/assets/icon/More_vertical.svg')} class='export-more'/>
              </a-dropdown>
            ];
          }

        }
      ])
    };
  },
  computed: {
    ...mapState('templateManagement', [
      'repReportTemplateLoading',
      'repReportTemplateList',
      'addRepReportTemplateLoading',
      'paginationOptions'
    ]),

    checkSwitch: {
      get() {
        return Boolean(this.addForm.enable);
      },
      set(nv) {
        this.$set(this.addForm, 'enable', +nv);
      }
    }
  },
  watch: {
    'addForm.tailNumbers'(nv, ov) {
      if (nv) {
        this.$nextTick(() => {
          this.$refs.addForm?.validateField('tailNumbers');
        });
      }
    }
  },
  mounted() {
    // 获取一级分类
    this.getSmiList();

    this.changeTable({ current: 1 });
  },
  methods: {
    ...mapMutations('templateManagement', [
      'setState'
    ]),
    ...mapActions('templateManagement', [
      'getRepReportTemplateList',
      'addRepReportTemplate',
      'deleteRepReportTemplate',
      'modifyRepReportTemplateByEnable',
      'modifyRepReportTemplate'
    ]),
    changeTable({ current, pageSize = 10 }) {
      if (pageSize !== this.paginationOptions.pageSize) {
        current = 1;
      }
      this.setState({ key: 'paginationOptions', payload: { ...this.paginationOptions, pageNum: current, pageSize }});
      this.getData();
    },
    // 重置
    resetSearchHandler() {
      this.search = {};

      this.changeTable({ current: 1 });
    },
    // 新增/修改
    addConfirmHandler() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.addForm.id) {
            this.modifyRepReportTemplate(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.getData();
              }
            });
          } else {
            this.addRepReportTemplate(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.getData();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 确认删除
    delItemHandler(id) {
      this.deleteRepReportTemplate({ id }).then((rep) => {
        if (rep) {
          this.getData();
        }
      });
    },
    // 切换状态
    changeEnableHandler(id, enable, index) {
      const params = {
        id,
        enable: +!enable
      };
      this.modifyRepReportTemplateByEnable(params).then((rep) => {
        if (rep) {
          this.getData();
        }
      });
    },
    // 复制
    copyItemHandler(row) {
      const { description, enable, imi, smi, tailNumbers, templateName } = row;
      const params = { description, enable, imi, smi, tailNumbers, templateName };
      this.addRepReportTemplate(params).then((rep) => {
        if (rep) {
          this.getData();
        }
      });
    },
    // 修改预赋值
    modifyHandler(row) {
      this.addVisible = true;
      row.tailNumbers === null ? row.tailNumbers = [] : '';
      this.addForm = { ...row };
      this.addTitle = '修改';
    },
    // 关闭add
    cancelHandler() {
      this.addForm = { enable: 0 };
      this.addTitle = '新增';
      this.$refs.addForm.resetFields();
      this.setState({ key: 'secondaryClassificationListModel', payload: {}});
    },
    goVersion({ id, templateName, version, imi, smi }) {
      if (smi === 'ENG') {
        const routerP = {
          path: '/versionManagementEng',
          query: {
            id,
            templateName,
            version,
            imi,
            smi
          }
        };
        this.$router.push(routerP);
      } else {
        const routerP = {
          path: '/versionManagement',
          query: {
            id,
            templateName,
            version,
            imi,
            smi
          }
        };
        this.$router.push(routerP);
      }
    },
    // 获取table
    getData() {
      this.getRepReportTemplateList(this.search);
    }

  }
};
</script>

<style lang='less'>
.tmp-drop-down{
  .ant-dropdown-menu{
    width: 94px;
  }
}
</style>
